import CryptoJS from 'crypto-js/crypto-js'

// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse("1111222233334444"); //""中与后台一样  密码
const IV = CryptoJS.enc.Utf8.parse(); //""中与后台一样

/**
 * AES加密 ：字符串 key iv  返回base64
 */
export function Encrypt(word, keyStr, ivStr) {
    let key = KEY
    let iv = IV

    if (keyStr) {
        key = CryptoJS.enc.Utf8.parse(keyStr);
        iv = CryptoJS.enc.Utf8.parse(ivStr);
    }

    let byteContent = CryptoJS.enc.Hex.parse(word);
    var encrypted = CryptoJS.AES.encrypt(byteContent, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    // console.log("-=-=-=-", encrypted.ciphertext)
    // return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    return encrypted.toString(CryptoJS.enc.Utf8);
}

/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
export function Decrypt(word) {
    let key = KEY
    console.log("key"+key)
    console.log("word"+word)
    
    // 1 . 16进制转2进制
    // let byteContent = HexString2Bytes(word);
    // stringify / parse
    let byteContent = CryptoJS.enc.Hex.stringify(word);
    console.log(byteContent)
    // let src = CryptoJS.enc.Hex.stringify(hexContent);
    // 2 . 解密
    var decrypt = CryptoJS.AES.decrypt(byteContent, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    console.log("啥时候他解析出来了就对了；decrypt:"+decrypt.toString(CryptoJS.enc.Utf8))
    // 3. 汉化
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

//十六进制字符串转字节数组，跟网上demo一样
function HexString2Bytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
        console.log("就发哦是发动机")
        return null;
    }
    len /= 2;
    var arrBytes = new Array();
    for (var i = 0; i < len; i++) {
        var s = str.substr(pos, 2);
        var v = parseInt(s, 16);
        arrBytes.push(v);
        pos += 2;
    }
    console.log(arrBytes)
    return arrBytes;
}

//字节数组转十六进制字符串，对负值填坑
function Bytes2HexString(arrBytes) {
    var str = "";
    for (var i = 0; i < arrBytes.length; i++) {
        var tmp;
        var num = arrBytes[i];
        if (num < 0) {
            //此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
            tmp = (255 + num + 1).toString(16);
        } else {
            tmp = num.toString(16);
        }
        if (tmp.length == 1) {
            tmp = "0" + tmp;
        }
        str += tmp;
    }
    return str;
}